package com.tapstitch.scm.common.core.context;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.bluebuck.sso.client.admin.auth.model.LoginUser;
import com.bluebuck.sso.client.model.scope.DsData;
import com.bluebuck.sso.client.model.scope.DsUserData;
import lombok.Getter;
import lombok.Setter;
import org.springframework.web.context.request.WebRequestInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liyang
 * @date 2024/7/2 16:07
 */
public class LoginUserContext {

    protected static final ThreadLocal<Context> REQUEST_CONTEXT = new InheritableThreadLocal<>();

    private LoginUserContext() {

    }

    public static Context getContext() {
        Context context = REQUEST_CONTEXT.get();
        if (context == null) {
            context = new Context();
            REQUEST_CONTEXT.set(context);
        }
        return context;
    }

    public static void setContext(Context context) {
        if (context == null) {
            REQUEST_CONTEXT.remove();
        } else {
            REQUEST_CONTEXT.set(context);
        }
    }


    public static String getRealName() {
        Context context = getContext();
        if (context == null || context.getCurrentUser() == null) {
            return "系统默认账户";
        }
        return context.getCurrentUser().getRealName();
    }

    public static Long getUserId() {
        Context context = getContext();
        if (context == null || context.getCurrentUser() == null) {
            return 0L;
        }
        return context.getCurrentUser().getUserId();
    }


    //获取权限数据  -- 目前只有仓库权限
    public static List<String> getWarehouseCodeList() {
        Context context = getContext();
        if (context == null || context.getUserData() == null) {
            return null;
        }
        List<DsData> dataList = context.getUserData().getDataList();
        if(CollectionUtil.isEmpty(dataList) || dataList.size() < 1){
            //如果没有分配仓库权限  则设置一个不存在的仓库编码值
            return ListUtil.toList("-1");
        }
        return dataList.stream().map(DsData::getVal).collect(Collectors.toList());
    }

    @Getter
    @Setter
    public static class Context {

        /**
         * 当前登录用户
         */
        private LoginUser currentUser;

        /**
         * 当前用户数据权限范围，目前只是一个实例，建议根据业务使用场景重新封装实体，并在下面方法修改
         *
         * @see WebRequestInterceptor#preHandle(HttpServletRequest, HttpServletResponse, Object)
         */
        private DsUserData userData;

    }

}
